package com.hy.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.common.Result;
import com.hy.entity.Teacher;
import com.hy.mapper.SysTeacherMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
@Service
@Slf4j
public class SysTeacherImpl implements SysTeacher {
    @Autowired
    private SysTeacherMapper sysTeacherMapper;

    // 创建老师信息
    @Override
    public Result<Teacher> createTeacher(Teacher teacher) {
        try {
            // 设置创建时间和更新时间
            Date now = new Date();
            teacher.setCreateTime(now);
            teacher.setUpdateTime(now);

            // 保存老师信息
            sysTeacherMapper.insert(teacher);
            return Result.success("保存成功!");
        } catch (Exception e) {
            log.error("创建老师信息异常", e);
            return Result.error("创建老师信息异常：" + e.getMessage());
        }
    }

    // 获取所有老师信息
    // 分页获取老师信息
    @Override
    public Result<IPage<Teacher>> getTeacherPage(Integer pageNum, Integer pageSize, String teacherName, Integer minLikes, Integer maxLikes) {
        try {
            // 处理分页参数，使用 MyBatis-Plus 的 Page 自动处理默认值（更简洁）
            Page<Teacher> page = new Page<>(pageNum != null && pageNum > 0 ? pageNum : 1,
                    pageSize != null && pageSize > 0 ? pageSize : 10);

            // 正确初始化 LambdaQueryWrapper
            LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();

            // 添加基本条件（使用 Lambda 表达式，类型安全）
            queryWrapper.eq(Teacher::getDeleteFlag, 0) // 对应数据库字段 deleteFlag（需与实体类属性匹配）
                    .orderByDesc(Teacher::getCreateTime); // 对应数据库字段 createTime

            // 添加动态查询条件（Lambda 表达式版）
            if (teacherName != null && !teacherName.isEmpty()) {
                queryWrapper.like(Teacher::getTeacherName, teacherName); // 假设实体类属性为 teacherName
            }
            if (minLikes != null) {
                queryWrapper.ge(Teacher::getTeacherLikeNumbers, minLikes); // 大于等于
            }
            if (maxLikes != null) {
                queryWrapper.le(Teacher::getTeacherLikeNumbers, maxLikes); // 小于等于
            }

            IPage<Teacher> teacherPage = sysTeacherMapper.selectPage(page, queryWrapper);
            return Result.success(teacherPage);
        } catch (Exception e) {
            log.error("分页获取老师列表异常: {}", e.getMessage(), e); // 记录完整异常信息
            return Result.error("分页获取老师列表失败，请联系管理员"); // 隐藏具体异常细节，返回友好提示
        }
    }

    // 根据 ID 获取老师信息
    @Override
    public Result<Teacher> getTeacherById(Long id) {
        try {
            if (id == null) {
                return Result.error("老师ID不能为空");
            }

            // 查询未删除的老师
            QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("id", id)
                    .eq("deleteFlag", 0);

            Teacher teacher = sysTeacherMapper.selectOne(queryWrapper);
            if (teacher != null) {
                return Result.success(teacher);
            } else {
                return Result.error("未找到该老师信息");
            }
        } catch (Exception e) {
            log.error("获取老师信息异常，ID={}", id, e);
            return Result.error("获取老师信息异常：" + e.getMessage());
        }
    }

    // 更新老师信息
    @Override
    public Result<Teacher> updateTeacher(Teacher teacher) {
        try {
            if (teacher.getId() == null) {
                return Result.error("老师ID不能为空");
            }

            // 检查老师是否存在
            Teacher teacher1 = sysTeacherMapper.selectById(teacher.getId());
            if (teacher1 == null || teacher1.getDeleteFlag() == 1) {
                return Result.error("未找到该老师信息");
            }
            sysTeacherMapper.updateById(teacher);
            return Result.success("修改成功!");
        } catch (Exception e) {
            log.error("更新老师信息异常，ID={}", teacher.getId(), e);
            return Result.error("更新老师信息异常：" + e.getMessage());
        }
    }

    // 根据 ID 删除老师信息（逻辑删除）
    @Override
    public Result<String> deleteTeacher(Long id) {
        try {
            if (id == null) {
                return Result.error("老师ID不能为空");
            }

            // 检查老师是否存在
            Teacher teacher = sysTeacherMapper.selectById(id);
            if (teacher == null || teacher.getDeleteFlag() == 1) {
                return Result.error("未找到该老师信息");
            }

            // 逻辑删除：设置deleteFlag=1并更新时间
            teacher.setDeleteFlag(1);
            teacher.setUpdateTime(new Date());
            sysTeacherMapper.updateById(teacher);
            return Result.success("删除成功!");
        } catch (Exception e) {
            log.error("删除老师信息异常，ID={}", id, e);
            return Result.error("删除老师信息异常：" + e.getMessage());
        }
    }
}
